#include <stdio.h>
#include <string.h>
void removeExtraSpace(char *str)
{
    int pos = 0;
    int length = strlen(str);
    /* 1.找到第一个不为空格的位置 */
    int idx = 0;
    while (str[idx] == ' ')
    {
        idx++;
    }
    /*什么时候退出循环?第一个不为空格的位置.*/
    for (; idx < length; idx++)
    {
        if (str[idx] != ' ')
        {
            str[pos] = str[idx];
            pos++;
        }
        else
        {
            if (str[idx + 1] != ' ' && str[idx + 1] != '\0')
            {
                str[pos] = ' ';
                pos++;
            }
        }
    }
    str[pos] = '\0';
}

void ReverseOrder(char *str, int left, int right)
{
    right--;
    while (left < right)
    {
        char tmp = str[left];
        str[left] = str[right];
        str[right] = tmp;

        left++;
        right--;
    }
}

int main()
{
    char buffer[] = "   welcome    to   jiangshu    nanjing.    ";
    //"nanjing. jiangshu to welcome"

    /*第-步:去掉多余空格 */
    //"welcome to jiangshu nanjing"
    removeExtraSpace(buffer);

    /*第二步:将整个字符串逆序 */
    //"gnijnan uhsgnaij ot emoclew"
    ReverseOrder(buffer, 0, strlen(buffer));
   

    /*第三步:将每一个单词逆序*/
    //"nanjing jiangshu to welcome";
    int length = strlen(buffer);
    int start = 0;
    int end = 0;
    for (int idx = 0; idx < length; idx++)
    {
        if (buffer[idx] == ' ')
        {
            end = idx;
            ReverseOrder(buffer, start, end);

            start = end + 1;
        }
    }
    ReverseOrder(buffer, start, length);
    printf("buffer=%s\n", buffer);
    return 0;
}
